package cn.gdut.chengcai.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import cn.gdut.chengcai.entity.KeyValueInfo;
import cn.gdut.chengcai.entity.KeyValueInfoExample;
import cn.gdut.chengcai.service.KeyValueInfoService;
import cn.gdut.chengcai.vo.SystemSettingVo;

public class SystemSettingUtil {
	public static Map<String, KeyValueInfo> getLastestSystemSettingMap(KeyValueInfoService service) {
		Map<String, KeyValueInfo> mapSetting = new HashMap<>();

		KeyValueInfoExample example = new KeyValueInfoExample();
		example.createCriteria();
		List<KeyValueInfo> listSetting = service.selectByExample(example);
		for (KeyValueInfo setting : listSetting) {
			mapSetting.put(setting.getKey(), setting);
		}

		return mapSetting;
	}

	public static SystemSettingVo getVo(KeyValueInfoService service, HttpSession session) {
		Map<String, KeyValueInfo> mapSetting = getLastestSystemSettingMap(service);
		SystemSettingVo vo = new SystemSettingVo();
		vo.setDefaultMailHost(mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_HOST).getValue());
		vo.setDefaultMailPort(mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_PORT).getValue());
		vo.setDefaultMailUsername(mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_USERNAME).getValue());
		vo.setDefaultMailPassword(mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_PASSWORD).getValue());
		vo.setDefaultConfigIsOpenRegister(
				mapSetting.get(SystemConstantUtil.DEFAULT_CONFIG_IS_OPEN_REGISTER).getValue());
		vo.setDefaultConfigIsOpenLogin(mapSetting.get(SystemConstantUtil.DEFAULT_CONFIG_IS_OPEN_LOGIN).getValue());
		return vo;
	}

	public static void updateDb(KeyValueInfoService service, SystemSettingVo vo) {
		Map<String, KeyValueInfo> mapSetting = getLastestSystemSettingMap(service);

		KeyValueInfo info = null;

		info = mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_HOST);
		info.setValue(vo.getDefaultMailHost());
		service.updateByPrimaryKey(info);

		info = mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_PORT);
		info.setValue(vo.getDefaultMailPort());
		service.updateByPrimaryKey(info);

		info = mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_USERNAME);
		info.setValue(vo.getDefaultMailUsername());
		service.updateByPrimaryKey(info);

		info = mapSetting.get(SystemConstantUtil.DEFAULT_MAIL_PASSWORD);
		info.setValue(vo.getDefaultMailPassword());
		service.updateByPrimaryKey(info);

		info = mapSetting.get(SystemConstantUtil.DEFAULT_CONFIG_IS_OPEN_LOGIN);
		info.setValue(vo.getDefaultConfigIsOpenLogin());
		service.updateByPrimaryKey(info);

		info = mapSetting.get(SystemConstantUtil.DEFAULT_CONFIG_IS_OPEN_REGISTER);
		info.setValue(vo.getDefaultConfigIsOpenRegister());
		service.updateByPrimaryKey(info);
	}

}
